﻿using System;
using System.Collections.Concurrent;
using Windows.ApplicationModel.Activation;
using Windows.Foundation.Collections;

namespace FLAC_WinRT.Example.App
{
    public interface IContinuable
    {
        void Continue(IContinuationActivatedEventArgs args);
    }

    public static class ContinuationManager
    {
        private const string CONTINUATION_ID = "ContinuationId";

        private static ConcurrentDictionary<Guid, IContinuable> _continuationRegistry;

        public static bool Register(IContinuable continuable, ValueSet continuationData)
        {
            if (_continuationRegistry == null)
                _continuationRegistry = new ConcurrentDictionary<Guid, IContinuable>();

            var continuationId = Guid.NewGuid();
            bool result = false;

            if (result = _continuationRegistry.TryAdd(continuationId, continuable))
                continuationData.Add(CONTINUATION_ID, continuationId);

            return result;
        }

        public static void Continue(IContinuationActivatedEventArgs args)
        {
            if (args == null)
                throw new ArgumentNullException("args");

            object continuationId;
            if (args.ContinuationData.TryGetValue(CONTINUATION_ID, out continuationId) && continuationId is Guid)
            {
                var id = (Guid)continuationId;
                IContinuable continuable;
                if (_continuationRegistry.TryRemove(id, out continuable))
                    continuable.Continue(args);
            }

            // Clear incorrect entries
            _continuationRegistry.Clear();
        }
    }
}
